package kidsProjectServer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.AbstractMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

public class BootstrapServer {

	public static final int PORT = 8988;
	public static ServerSocket ss;
	public BufferedReader in;
	public PrintWriter out;
	public BufferedReader br;
	public String opseg;

	public static List<Entry<InetAddress, Integer>> lastClients;

	public BootstrapServer() {
		URL url = getClass().getResource("confFile.txt");

		try {
			System.out.println(InetAddress.getLocalHost());
			File confs = new File(url.toURI());
			InputStreamReader isr = new InputStreamReader(new FileInputStream(
					confs));
			br = new BufferedReader(isr);
			opseg = br.readLine();
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {
		BootstrapServer bs = new BootstrapServer();
		lastClients = new LinkedList<Entry<InetAddress, Integer>>();

		ss = new ServerSocket(PORT, 0, InetAddress.getLocalHost());
		System.out.println("Pocinjem da slusam port");
		while (true) {
			Socket client = ss.accept();
			client.setReuseAddress(true);

			bs.in = new BufferedReader(new InputStreamReader(
					client.getInputStream()));
			bs.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
					client.getOutputStream())), true);

			// System.out.println(bs.in.readLine());
			System.out.println("Client connected!");
			bs.out.println(bs.opseg);
			for (Entry<InetAddress, Integer> clientEntry : lastClients) {
				bs.out.println(clientEntry.getKey().getHostAddress());
				bs.out.println(clientEntry.getValue());
			}
			bs.out.println("#FINISHED_SENDING_LAST_CLIENTS$");
			InetAddress address = client.getInetAddress();
			Integer port = client.getPort();
			System.out.println(address.getHostAddress() + " " + port);
			Entry<InetAddress, Integer> clientEntry = new AbstractMap.SimpleEntry<InetAddress, Integer>(
					address, port);
			lastClients.add(clientEntry);
			if (lastClients.size() > 10)
				lastClients.remove(0);

			client.close();
			// System.out.println(bs.in.readLine());
			// System.out.println(bs.in.readLine());
		}
	}
}
